package com.ayf.payment.game.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.dto.AybUserDTO;
import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.dto.MerchantPermissionDTO;
import com.ayf.payment.game.api.dto.Token;
import com.ayf.payment.game.api.dto.platform.NetConfigDTO;
import com.ayf.payment.game.api.entity.AybUser;
import com.ayf.payment.game.api.entity.LoginHistory;
import com.ayf.payment.game.api.entity.Merchant;
import com.ayf.payment.game.api.entity.MerchantSon;
import com.ayf.payment.game.api.exception.LogicalException;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.service.*;
import com.ayf.payment.game.api.service.platform.NetConfigService;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.type.LoginType;
import com.ayf.payment.game.api.utils.*;
import com.ayf.payment.game.api.wx.WxSendMsgUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 商户绑定爱游宝控制层
 * @Author: zh-liang
 * @Date : 2021-03-16 11:21
 */
@RestController
@RequestMapping("/v/merchant/ayb")
public class AybUserController {

    @Autowired
    private RedisCacheUtil redisCacheUtil;
    @Autowired
    private AybUserService aybUserService;
    @Autowired
    private NetConfigService netConfigService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private MerchantPermissionService merchantPermissionService;
    @Autowired
    private MerchantSonService merchantSonService;
    @Autowired
    private LoginHistoryService loginHistoryService;
    @Autowired
    private WxSendMsgUtils wxSendMsgUtils;
    private static final String AYB_SCAN_CALLBACK_URL = System.getenv("AYB_SCAN_CALLBACK_URL");
    private static final String PLATFORM_CODE = System.getenv("GAME_AYFPAY_PLATFORM_CODE");

    /**
     * 获取爱游宝绑定信息
     */
    @GetMapping("/getAybUser")
    public CommonResult<Object> getAybUser(MerchantDTO merchantDTO) {
        AybUser aybUser = aybUserService.getBindAybUser(merchantDTO.getId(), merchantDTO.getLoginId());
        if (aybUser == null) {
            Long time = 60 * 60L;
            String uuid = SnowFlakeUtils.getUniqueId();
            String key = "bind" + uuid;
            String domainName = netConfigService.getNetConfig().getDomainName();
            domainName = domainName + "/gameapip/v3/merchant/ayb/bind/" + uuid;
            String url = AYB_SCAN_CALLBACK_URL + "/ayb-api/p1/ayb/bind?url=" + domainName + "&code=" + PLATFORM_CODE;
            Map<String, Object> map = new HashMap<>(8);
            map.put("type", "bind");
            map.put("account", merchantDTO.getLoginAccount());
            map.put("url", url);
            redisCacheUtil.setObjectToCacheDelaySeconds(uuid, merchantDTO, time);
            redisCacheUtil.setObjectToCacheDelaySeconds(key, map, time);
            return new CommonResult<>(200, "获取成功", "/v/merchant/ayb/getQrCode/" + key);
        } else {
            return new CommonResult<>(199, "获取成功", aybUser);
        }
    }

    /**
     * 获取二维码
     */
    @GetMapping("/getQrCode/{key}")
    public void getQrCode(HttpServletResponse response, @PathVariable("key") String key) {
        Map<String, Object> val = redisCacheUtil.getObjectFromCache(key);
        if (val == null) {
            throw new ParameterException("请刷新页面重新获取");
        }
        try {
            String domainName = netConfigService.getNetConfig().getDomainName();
            String url = domainName + "/gameapip/v4/qrCode/" + key;
            Map<String, Object> map = new HashMap<>(8);
            map.put("type", val.get("type"));
            map.put("url", url);
            QrCodeUtils.encode(JSONObject.toJSONString(map), response.getOutputStream());
        } catch (Exception e) {
            String traceId = SnowFlakeUtils.getTraceId();
            throw new LogicalException("[{}]key[{}]获取爱游宝账户二维码失败,发生[{}]异常,异常信息为[{}]", traceId, key,
                    e.getClass().getSimpleName(), e.getMessage());
        }
    }

    /**
     * 获取解绑爱游宝二维码url
     */
    @GetMapping("/getUnBindQrCodeUrl")
    public CommonResult<Map<String, String>> getUnBindQrCodeUrl(MerchantDTO merchantDTO) {
        long time = 60 * 60L;
        String uuid = SnowFlakeUtils.getUniqueId();
        String key = "unbind" + uuid;
        String domainName = netConfigService.getNetConfig().getDomainName();
        domainName = domainName + "/gameapip/v3/merchant/ayb/unbind/" + uuid;
        String url = AYB_SCAN_CALLBACK_URL + "/ayb-api/p1/ayb/unbind?url=" + domainName + "&code=" + PLATFORM_CODE;
        Map<String, Object> map2 = new HashMap<>(8);
        map2.put("type", "unbind");
        map2.put("account", merchantDTO.getLoginAccount());
        map2.put("url", url);
        redisCacheUtil.setObjectToCacheDelaySeconds(uuid, merchantDTO, time);
        redisCacheUtil.setObjectToCacheDelaySeconds(key, map2, time);
        Map<String, String> map = new HashMap<>();
        map.put("key", uuid);
        map.put("url", "/v/merchant/ayb/getQrCode/" + key);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取成功", map);
    }

    /**
     * 获取解绑爱游宝二维码的扫描状态
     */
    @GetMapping("/getUnBindStatus")
    public CommonResult<Object> getUnBindStatus(@RequestParam("key") String key) {
        if (StringUtils.isEmpty(key)) {
            throw new ParameterException("key不能为空");
        }
        Integer status = redisCacheUtil.getObjectFromCache("AYB_UN_BIND_STATUS:" + key);
        if (status == null) {
            status = 0;
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取成功", status);
    }

    /**
     * 更改是否接收异常消息提醒状态
     */
    @PostMapping("/updateAybMsgStatus")
    public CommonResult<Object> updateAybMsgStatus(@RequestBody AybUserDTO aybUserDTO) {
        if (aybUserDTO.getId() == null) {
            throw new ParameterException("id不能为空");
        }
        aybUserService.updateAybMsgStatus(aybUserDTO);
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "修改成功");
    }

    /**
     * 获取爱游宝登录二维码
     */
    @GetMapping("/getAybLoginQrCode/{key}")
    public void getAybLoginQrCode(HttpServletResponse response, @PathVariable("key") String key) {
        if (StringUtils.isEmpty(key)) {
            throw new ParameterException("key不能为空");
        }
        String url = AYB_SCAN_CALLBACK_URL + "/ayb-api/p1/ayb/getLoginInfo?url=" + netConfigService.getNetConfig().getDomainName() + "/gameapip/v3/merchant/ayb/getBindInfo/" + key + "&code=" + PLATFORM_CODE;
        try {
            Map<String, Object> map = new HashMap<>(8);
            map.put("type", "login");
            map.put("url", url);
            QrCodeUtils.encode(JSONObject.toJSONString(map), response.getOutputStream());
        } catch (Exception e) {
            String traceId = SnowFlakeUtils.getTraceId();
            throw new LogicalException("[{}]key[{}]获取爱游宝账户二维码失败,发生[{}]异常,异常信息为[{}]", traceId, key,
                    e.getClass().getSimpleName(), e.getMessage());
        }
    }

    /**
     * 获取登录爱游宝二维码的扫描状态
     */
    @PostMapping("/getAybLoginStatus/{key}")
    public CommonResult<Object> getAybLoginStatus(@PathVariable("key") String key, HttpServletRequest request) {
        if (StringUtils.isEmpty(key)) {
            throw new ParameterException("key不能为空");
        }
        Token token = redisCacheUtil.getObjectFromCache("AYB_LOGIN_STATUS:" + key);
        if (token == null) {
            return new CommonResult<>(196, "登录失败,二维码还未扫描");
        }
        HashMap<String, Object> result = new HashMap<>(8);
        result.put("accessToken", token.getAccessToken());
        String loginAccount = "";
        if (LoginType.FATHER.name().equals(token.getLoginType())) {
            Merchant merchant = merchantService.find(token.getMerchantId());
            if (merchant == null) {
                return new CommonResult<>(CommonConstants.RETURN_ERROR, "进入商户后台失败，不存在此商户");
            }
            loginAccount = merchant.getLoginAccount();
            result.put("merchantStatus", merchant.getStatus().name());
            result.put("merchantType", merchant.getMerchantType());
            MerchantPermissionDTO dto = merchantPermissionService.adminList(merchant.getMerchantType());
            result.put("permission", dto);
        } else {
            MerchantSon merchantSon = merchantSonService.selectInfo(token.getLoginId());
            if (merchantSon == null) {
                return new CommonResult<>(CommonConstants.RETURN_ERROR, "进入商户后台失败，不存在此商户");
            }
            loginAccount = merchantSon.getLoginAccount();
            MerchantPermissionDTO dto = merchantPermissionService.sonPermissionList(merchantSon.getRoleId());
            result.put("permission", dto);
        }
        result.put("accessToken", token.getAccessToken());
        result.put("loginType", "oneself");
        NetConfigDTO netConfig = netConfigService.getNetConfig();
        result.put("domainName", netConfig.getDomainName());
        result.put("type", token.getLoginType());
        addLoginHistory(token.getLoginId(), request);
        wxSendMsgUtils.login(token.getMerchantId(), token.getLoginId(), loginAccount,
                "爱游宝扫码登录", IPUtils.getIp(request));
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "获取成功", result);
    }

    public void addLoginHistory(Integer merchantId, HttpServletRequest request) {
        String ip = IPUtils.getIp(request);
        LoginHistory loginHistory = new LoginHistory();
        loginHistory.setLoginIp(ip);
        loginHistory.setLoginCity("未知");
        loginHistory.setMerchantId(merchantId);
        loginHistory.setLoginTime(new Date());
        String system = "其它";
        String agent = request.getHeader("user-agent");
        if (agent.contains("Windows")) {
            system = "Windows客户端";
        } else if (agent.contains("Mac")) {
            system = "Mac客户端";
        } else if (agent.contains("Android")) {
            system = "Android移动客户端";
        } else if (agent.contains("iPad")) {
            system = "iPad客户端";
        } else if (agent.contains("iPhone")) {
            system = "iPhone移动客户端";
        }
        loginHistory.setLoginSystem(system);
        //增加登录记录
        loginHistoryService.insert(loginHistory);

        // 更新商户的最后一次登录时间
        Merchant merchant = new Merchant();
        merchant.setId(merchantId);
        merchant.setLoginTime(DateUtils.getNowDate());
        merchantService.update(merchant);
    }
}
